package org.c797797ty.railway;

import org.c797797ty.railway.manager.UserSessionManager;
import org.c797797ty.railway.model.User;
import org.c797797ty.railway.service.ConcurrentTicketService;
import org.c797797ty.railway.service.ConcurrentUserService;
import org.c797797ty.railway.util.ConcurrentDBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
 * @author C797797ty
 * @data 2025/11/4 14:38
 */

/**
 * 高并发铁路购票系统主类
 */
public class ConcurrentRailwaySystem {
    private static final ExecutorService executor = Executors.newFixedThreadPool(10);
    private static final Scanner scanner = new Scanner(System.in); // 使用单一的Scanner实例

    public static void main(String[] args) {
        System.out.println("===== 高并发铁路售票系统 =====");

        while (true) {
            System.out.println("\n1. 用户登录");
            System.out.println("2. 用户注册");
            System.out.println("3. 管理员登录");
            System.out.println("4. 退出");
            System.out.print("请选择操作: ");

            try {
                int choice = scanner.nextInt();
                scanner.nextLine();  // 消耗换行符

                switch (choice) {
                    case 1:
                        login();
                        break;
                    case 2:
                        register();
                        break;
                    case 3:
                        adminLogin();
                        break;
                    case 4:
                        System.out.println("感谢使用，再见！");
                        executor.shutdownNow();
                        System.exit(0);
                    default:
                        System.out.println("无效的选择，请输入1-4之间的数字");
                }
            } catch (InputMismatchException e) {
                System.err.println("输入错误: 请输入数字");
                scanner.nextLine(); // 清除错误的输入
            } catch (Exception e) {
                System.err.println("发生错误: " + e.getMessage());
                scanner.nextLine(); // 清除错误的输入
            }
        }
    }

    // 初始化管理员账户
    private static void initAdminAccount() {
        try {
            // 检查是否存在管理员账户
            Boolean adminExists = ConcurrentDBUtil.executeQuery(rs -> {
                return rs.next();
            }, "SELECT * FROM users WHERE role = 'admin' LIMIT 1");

            if (!adminExists) {
                // 创建默认管理员账户
                ConcurrentDBUtil.executeInTransaction(conn -> {
                    try (PreparedStatement stmt = conn.prepareStatement(
                            "INSERT INTO users (username, password, role) VALUES (?, ?, 'admin')")) {
                        stmt.setString(1, "admin");
                        stmt.setString(2, "admin123");
                        stmt.executeUpdate();
                    }
                });
                System.out.println("已创建默认管理员账户: 用户名=admin, 密码=admin123");
            }
        } catch (SQLException e) {
            System.err.println("初始化管理员账户失败: " + e.getMessage());
        }
    }


    private static void login() {
        try {
            System.out.print("用户名: ");
            String username = scanner.nextLine();
            System.out.print("密码: ");
            String password = scanner.nextLine();

            System.out.println("开始登录流程...");
            System.out.println("输入用户名: " + username);
            System.out.println("输入密码: " + password);

            // 直接执行登录，不使用线程池
            try {
                String token = ConcurrentUserService.login(username, password);
//                System.out.println("登录方法返回，token: " + token);
                if (token != null) {
                    System.out.println("登录成功，进入用户菜单");
                    userSessionMenu(token);
                } else {
                    System.out.println("登录失败，用户名或密码错误");
                }
            } catch (SQLException e) {
                System.err.println("登录失败: " + e.getMessage());
                e.printStackTrace();
            }
        } catch (Exception e) {
            System.err.println("登录出错: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private static void register() {
        try {
            System.out.print("新用户名: ");
            String username = scanner.nextLine();
            System.out.print("新密码: ");
            String password = scanner.nextLine();

            executor.submit(() -> {
                try {
                    ConcurrentUserService.register(username, password);
                } catch (SQLException e) {
                    System.err.println("注册失败: " + e.getMessage());
                }
            });
        } catch (Exception e) {
            System.err.println("注册出错: " + e.getMessage());
        }
    }


    private static void adminLogin() {
        try {
            System.out.print("管理员用户名: ");
            String username = scanner.nextLine();
            System.out.print("管理员密码: ");
            String password = scanner.nextLine();

            // 直接执行登录，不使用线程池
            try {
                String token = ConcurrentUserService.adminLogin(username, password);
                if (token != null) {
                    System.out.println("管理员登录成功，进入管理员菜单");
                    adminSessionMenu(token);
                } else {
                    System.out.println("管理员登录失败，用户名或密码错误");
                }
            } catch (SQLException e) {
                System.err.println("管理员登录失败: " + e.getMessage());
                e.printStackTrace();
            }
        } catch (Exception e) {
            System.err.println("管理员登录出错: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private static void adminSessionMenu(String token) {
        while (true) {
            User user = UserSessionManager.getSession(token);
            if (user == null) {
                System.out.println("管理员未登录或会话过期");
                return;
            }

            // 显示菜单标题和欢迎信息
            System.out.println("\n===== 管理员菜单 =====");
            System.out.println("欢迎，" + user.getUsername() + "！");

            // 显示菜单选项
            System.out.println("1. 查看所有候补订单");
            System.out.println("2. 处理候补订单");
            System.out.println("3. 退出登录");
            System.out.print("请选择操作: ");

            try {
                int choice = scanner.nextInt();
                scanner.nextLine();  // 消耗换行符

                switch (choice) {
                    case 1:
                        viewAllWaitingOrders();
                        break;
                    case 2:
                        processWaitingOrder();
                        break;
                    case 3:
                        UserSessionManager.invalidateSession(token);
                        return;
                    default:
                        System.out.println("无效的选择，请输入1-3之间的数字");
                }
            } catch (InputMismatchException e) {
                System.err.println("输入错误: 请输入数字");
                scanner.nextLine(); // 清除错误的输入
            }
        }
    }




    // 获取未读消息数量
    private static int getUnreadMessageCount(int userId) {
        try {
            return ConcurrentDBUtil.executeQuery(rs -> {
                if (rs.next()) {
                    return rs.getInt(1);
                }
                return 0;
            }, "SELECT COUNT(*) FROM system_messages WHERE user_id = ? AND is_read = 0", userId);
        } catch (SQLException e) {
            System.err.println("获取未读消息数量失败: " + e.getMessage());
            return 0;
        }
    }

    private static void userSessionMenu(String token) {
        while (true) {
            User user = UserSessionManager.getSession(token);
            if (user == null) {
                System.out.println("用户未登录或会话过期");
                return;
            }

            // 获取未读消息数量
            int unreadCount = getUnreadMessageCount(user.getId());

            // 显示菜单标题和欢迎信息
            if (unreadCount > 0) {
                System.out.println("\n===== 用户菜单 [" + unreadCount + "条未读消息] =====");
            } else {
                System.out.println("\n===== 用户菜单 =====");
            }
            System.out.println("欢迎，" + user.getUsername() + "！");

            // 显示菜单选项
            System.out.println("1. 查看所有车票");
            System.out.println("2. 查询车票");
            System.out.println("3. 购票");
            System.out.println("4. 帮他人购票");
            System.out.println("5. 查看我的订单");
            System.out.println("6. 退票");
            System.out.println("7. 查看系统消息");
            System.out.println("8. 查看候补订单");
            System.out.println("9. 退出登录");
            System.out.print("请选择操作: ");


            try {
                int choice = scanner.nextInt();
                scanner.nextLine();  // 消耗换行符

                switch (choice) {
                    case 1:
                        ConcurrentTicketService.displayTickets();
                        break;
                    case 2:
                        searchTicketsByRoute(token);
                        break;
                    case 3:
                        ConcurrentTicketService.bookTicket(token);
                        break;
                    case 4:
                        ConcurrentTicketService.bookTicketForOther(token);
                        break;
                    case 5:
                        viewUserOrders(token);
                        break;
                    case 6:
                        refundTicket(token);
                        break;
                    case 7:
                        viewSystemMessages(token);
                        break;
                    case 8:
                        viewWaitingOrders(token);
                        break;
                    case 9:
                        UserSessionManager.invalidateSession(token);
                        return;
                    default:
                        System.out.println("无效的选择，请输入1-9之间的数字");
                }
            } catch (InputMismatchException e) {
                System.err.println("输入错误: 请输入数字");
                scanner.nextLine(); // 清除错误的输入
            } catch (Exception e) {
                System.err.println("发生错误: " + e.getMessage());
                scanner.nextLine(); // 清除错误的输入
            }
        }
    }

    // 按出发地/目的地查询车票
    private static void searchTicketsByRoute(String token) {
        try {
            User user = UserSessionManager.getSession(token);
            if (user == null) {
                System.out.println("用户未登录或会话过期");
                return;
            }

            System.out.print("请输入出发地: ");
            String departure = scanner.nextLine();
            System.out.print("请输入目的地: ");
            String destination = scanner.nextLine();

            // 存储余票为0的车票ID
            final java.util.List<String> soldOutTickets = new java.util.ArrayList<>();

            // 使用新的API，通过回调函数处理ResultSet
            Boolean hasResults = ConcurrentDBUtil.executeQuery(rs -> {
                        System.out.println("\n===== 查询结果 =====");
                        boolean found = false;
                        while (rs.next()) {
                            found = true;
                            int availableSeats = rs.getInt("available_seats");
                            System.out.printf("[%s] %s→%s | %s | %s | %s | ¥%.2f | 余票: %d\n",
                                    rs.getString("ticket_id"),
                                    rs.getString("departure"),
                                    rs.getString("destination"),
                                    rs.getString("time"),
                                    rs.getString("time_slot"),
                                    rs.getString("seat_class"),
                                    rs.getDouble("price"),
                                    availableSeats);

                            // 如果余票为0，记录车票ID
                            if (availableSeats == 0) {
                                soldOutTickets.add(rs.getString("ticket_id"));
                            }
                        }
                        return found;
                    }, "SELECT * FROM tickets WHERE departure = ? AND destination = ?",
                    departure, destination);

            if (!hasResults) {
                System.out.println("未找到符合条件的车票");
                return;
            }

            // 如果有余票为0的车票，显示候补选项
            if (!soldOutTickets.isEmpty()) {
                System.out.println("\n===== 候补选项 =====");
                for (int i = 0; i < soldOutTickets.size(); i++) {
                    System.out.printf("%d. 为车票 [%s] 候补\n", i+1, soldOutTickets.get(i));
                }
                System.out.println("0. 返回");
                System.out.print("请选择操作: ");

                try {
                    int choice = scanner.nextInt();
                    scanner.nextLine();  // 消耗换行符

                    if (choice > 0 && choice <= soldOutTickets.size()) {
                        String ticketId = soldOutTickets.get(choice-1);
                        submitWaitingOrder(ticketId, user.getId());
                    } else if (choice != 0) {
                        System.out.println("无效的选择");
                    }
                } catch (InputMismatchException e) {
                    System.err.println("输入错误: 请输入数字");
                    scanner.nextLine(); // 清除错误的输入
                }
            }
        } catch (SQLException e) {
            System.err.println("查询失败: " + e.getMessage());
        }
    }

    // 提交候补订单
    private static void submitWaitingOrder(String ticketId, int userId) {
        try {
            System.out.println("正在提交候补订单...");

            // 获取车票信息
            Boolean hasTicket = ConcurrentDBUtil.executeQuery(rs -> {
                if (rs.next()) {
                    System.out.printf("车票信息: %s→%s | %s | %s | %s | ¥%.2f\n",
                            rs.getString("departure"),
                            rs.getString("destination"),
                            rs.getString("time"),
                            rs.getString("time_slot"),
                            rs.getString("seat_class"),
                            rs.getDouble("price"));
                    return true;
                }
                return false;
            }, "SELECT * FROM tickets WHERE ticket_id = ?", ticketId);

            if (!hasTicket) {
                System.out.println("车票不存在");
                return;
            }

            System.out.print("确认要候补该车票吗? (y/n): ");
            String confirm = scanner.nextLine();

            if ("y".equalsIgnoreCase(confirm)) {
                // 检查是否已经存在候补订单
                Boolean hasWaitingOrder = ConcurrentDBUtil.executeQuery(rs -> {
                            return rs.next();
                        }, "SELECT * FROM waiting_orders WHERE user_id = ? AND ticket_id = ? AND status = 'pending'",
                        userId, ticketId);

                if (hasWaitingOrder) {
                    System.out.println("您已经提交了该车票的候补订单，请勿重复提交");
                    return;
                }

                // 生成唯一的候补订单ID
                String waitingId = "WAIT-" + UUID.randomUUID().toString().substring(0, 8).toUpperCase();

                // 插入候补订单
                int result = ConcurrentDBUtil.executeUpdate(
                        "INSERT INTO waiting_orders (waiting_id, user_id, ticket_id, created_at, status) VALUES (?, ?, ?, NOW(), 'pending')",
                        waitingId, userId, ticketId);

                if (result > 0) {
                    System.out.println("候补订单已提交，请等候结果");
                    System.out.println("您的候补订单ID为: " + waitingId);
                } else {
                    System.out.println("提交候补订单失败");
                }
            } else {
                System.out.println("已取消候补订单");
            }
        } catch (SQLException e) {
            System.err.println("提交候补订单失败: " + e.getMessage());
        }
    }

    // 查看候补订单
    private static void viewWaitingOrders(String token) {
        try {
            User user = UserSessionManager.getSession(token);
            if (user == null) {
                System.out.println("用户未登录或会话过期");
                return;
            }

            // 使用循环，直到用户选择返回
            while (true) {
                // 使用新的API，通过回调函数处理ResultSet
                Boolean hasOrders = ConcurrentDBUtil.executeQuery(rs -> {
                            System.out.println("\n===== 我的候补订单 =====");
                            boolean found = false;
                            while (rs.next()) {
                                found = true;
                                System.out.printf("[%s] %s → %s | %s | %s | %s | 状态: %s | 提交时间: %s\n",
                                        rs.getString("waiting_id"),
                                        rs.getString("departure"),
                                        rs.getString("destination"),
                                        rs.getString("time"),
                                        rs.getString("time_slot"),
                                        rs.getString("seat_class"),
                                        rs.getString("status"),
                                        rs.getTimestamp("created_at"));
                            }
                            return found;
                        }, "SELECT wo.*, t.* " +
                                "FROM waiting_orders wo " +
                                "JOIN tickets t ON wo.ticket_id = t.ticket_id " +
                                "WHERE wo.user_id = ? AND wo.status = 'pending' " +
                                "ORDER BY wo.created_at DESC",
                        user.getId());

                if (!hasOrders) {
                    System.out.println("暂无候补订单");
                    return;
                }

                System.out.println("\n1. 取消候补订单");
                System.out.println("2. 查看候补历史");
                System.out.println("0. 返回");
                System.out.print("请选择操作: ");

                try {
                    int choice = scanner.nextInt();
                    scanner.nextLine();  // 消耗换行符

                    if (choice == 1) {
                        System.out.print("请输入要取消的候补订单ID: ");
                        String waitingId = scanner.nextLine();
                        boolean cancelled = cancelWaitingOrder(waitingId, user.getId());

                        // 如果取消成功，继续循环显示更新后的订单列表
                        if (cancelled) {
                            continue;
                        }
                    } else if (choice == 2) {
                        viewWaitingHistory(user.getId());
                    } else if (choice == 0) {
                        break; // 返回上级菜单
                    } else {
                        System.out.println("无效的选择");
                    }
                } catch (InputMismatchException e) {
                    System.err.println("输入错误: 请输入数字");
                    scanner.nextLine(); // 清除错误的输入
                }
            }
        } catch (SQLException e) {
            System.err.println("查询候补订单失败: " + e.getMessage());
        }
    }


    // 查看所有候补订单
    private static void viewAllWaitingOrders() {
        try {
            // 使用新的API，通过回调函数处理ResultSet
            Boolean hasOrders = ConcurrentDBUtil.executeQuery(rs -> {
                System.out.println("\n===== 所有候补订单 =====");
                boolean found = false;
                while (rs.next()) {
                    found = true;
                    System.out.printf("[%s] 用户ID: %d | %s → %s | %s | %s | %s | 状态: %s | 提交时间: %s\n",
                            rs.getString("waiting_id"),
                            rs.getInt("user_id"),
                            rs.getString("departure"),
                            rs.getString("destination"),
                            rs.getString("time"),
                            rs.getString("time_slot"),
                            rs.getString("seat_class"),
                            rs.getString("status"),
                            rs.getTimestamp("created_at"));
                }
                return found;
            }, "SELECT wo.*, t.* " +
                    "FROM waiting_orders wo " +
                    "JOIN tickets t ON wo.ticket_id = t.ticket_id " +
                    "WHERE wo.status = 'pending' " +
                    "ORDER BY wo.created_at DESC");

            if (!hasOrders) {
                System.out.println("暂无候补订单");
            }

            System.out.print("\n按回车键返回...");
            scanner.nextLine();
        } catch (SQLException e) {
            System.err.println("查询候补订单失败: " + e.getMessage());
        }
    }


    // 处理候补订单
    private static void processWaitingOrder() {
        try {
            System.out.print("请输入要处理的候补订单ID: ");
            String waitingId = scanner.nextLine();

            // 查询候补订单详情
            Boolean orderExists = ConcurrentDBUtil.executeQuery(rs -> {
                if (rs.next()) {
                    System.out.printf("\n订单详情:\n");
                    System.out.printf("订单ID: %s\n", rs.getString("waiting_id"));
                    System.out.printf("用户ID: %d\n", rs.getInt("user_id"));
                    System.out.printf("路线: %s → %s\n", rs.getString("departure"), rs.getString("destination"));
                    System.out.printf("时间: %s %s\n", rs.getString("time"), rs.getString("time_slot"));
                    System.out.printf("座位等级: %s\n", rs.getString("seat_class"));
                    System.out.printf("状态: %s\n", rs.getString("status"));
                    System.out.printf("提交时间: %s\n", rs.getTimestamp("created_at"));
                    return true;
                }
                return false;
            }, "SELECT wo.*, t.* " +
                    "FROM waiting_orders wo " +
                    "JOIN tickets t ON wo.ticket_id = t.ticket_id " +
                    "WHERE wo.waiting_id = ?", waitingId);

            if (!orderExists) {
                System.out.println("未找到该候补订单");
                return;
            }

            System.out.println("\n1. 确认候补订单");
            System.out.println("2. 取消候补订单");
            System.out.println("0. 返回");
            System.out.print("请选择操作: ");

            try {
                int choice = scanner.nextInt();
                scanner.nextLine();  // 消耗换行符

                switch (choice) {
                    case 1:
                        confirmWaitingOrder(waitingId);
                        break;
                    case 2:
                        cancelWaitingOrderByAdmin(waitingId);
                        break;
                    case 0:
                        return;
                    default:
                        System.out.println("无效的选择");
                }
            } catch (InputMismatchException e) {
                System.err.println("输入错误: 请输入数字");
                scanner.nextLine(); // 清除错误的输入
            }
        } catch (SQLException e) {
            System.err.println("处理候补订单失败: " + e.getMessage());
        }
    }


    // 确认候补订单
    // 确认候补订单
    private static void confirmWaitingOrder(String waitingId) {
        try {
            System.out.print("确认要处理该候补订单吗? (y/n): ");
            String confirm = scanner.nextLine();

            if ("y".equalsIgnoreCase(confirm)) {
                // 获取候补订单信息
                Boolean orderProcessed = ConcurrentDBUtil.executeQuery((ResultSet rs) -> {
                    if (rs.next()) {
                        int userId = rs.getInt("user_id");
                        String ticketId = rs.getString("ticket_id");
                        String seatClass = rs.getString("seat_class");

                        // 检查车票是否还有余票
                        try {
                            int availableSeats = ConcurrentDBUtil.executeQuery((ResultSet seatRs) -> {
                                if (seatRs.next()) {
                                    return seatRs.getInt("available_seats");
                                }
                                return 0;
                            }, "SELECT available_seats FROM tickets WHERE ticket_id = ? AND seat_class = ?", ticketId, seatClass);

                            // 检查用户是否已经拥有该车票
                            boolean hasTicket = ConcurrentDBUtil.executeQuery((ResultSet ticketRs) -> {
                                if (ticketRs.next()) {
                                    return ticketRs.getInt(1) > 0;
                                }
                                return false;
                            }, "SELECT COUNT(*) FROM user_tickets WHERE user_id = ? AND ticket_id = ?", userId, ticketId);

                            if (hasTicket) {
                                System.out.println("用户已拥有该车票，无法重复购买");
                                return false;
                            }

                            // 开始事务处理
                            ConcurrentDBUtil.executeInTransaction((Connection conn) -> {
                                // 如果没有余票，自动增加余票
                                if (availableSeats <= 0) {
                                    try (PreparedStatement updateTicketStmt = conn.prepareStatement(
                                            "UPDATE tickets SET available_seats = available_seats + 1 WHERE ticket_id = ? AND seat_class = ?")) {
                                        updateTicketStmt.setString(1, ticketId);
                                        updateTicketStmt.setString(2, seatClass);
                                        updateTicketStmt.executeUpdate();

                                        // 发送系统消息通知用户已增加余票
                                        try (PreparedStatement insertMessageStmt = conn.prepareStatement(
                                                "INSERT INTO system_messages (user_id, message_content, is_read, created_at) VALUES (?, ?, 0, NOW())")) {
                                            insertMessageStmt.setInt(1, userId);
                                            insertMessageStmt.setString(2, "您的候补订单 " + waitingId + " 已确认，由于原车票无余票，系统已自动为您增加余票");
                                            insertMessageStmt.executeUpdate();
                                        }

                                        System.out.println("该车票已无余票，已自动增加一张余票并通知用户");
                                    }
                                }

                                // 更新候补订单状态为已确认
                                try (PreparedStatement updateWaitingStmt = conn.prepareStatement(
                                        "UPDATE waiting_orders SET status = 'confirmed' WHERE waiting_id = ?")) {
                                    updateWaitingStmt.setString(1, waitingId);
                                    updateWaitingStmt.executeUpdate();
                                }

                                // 减少车票余票
                                try (PreparedStatement updateTicketStmt = conn.prepareStatement(
                                        "UPDATE tickets SET available_seats = available_seats - 1 WHERE ticket_id = ? AND seat_class = ?")) {
                                    updateTicketStmt.setString(1, ticketId);
                                    updateTicketStmt.setString(2, seatClass);
                                    updateTicketStmt.executeUpdate();
                                }

                                // 添加用户订单
                                try (PreparedStatement insertOrderStmt = conn.prepareStatement(
                                        "INSERT INTO user_tickets (user_id, ticket_id, seat_class, created_at) VALUES (?, ?, ?, NOW())")) {
                                    insertOrderStmt.setInt(1, userId);
                                    insertOrderStmt.setString(2, ticketId);
                                    insertOrderStmt.setString(3, seatClass);
                                    insertOrderStmt.executeUpdate();
                                }

                                // 如果有余票，发送常规确认消息
                                if (availableSeats > 0) {
                                    // 添加系统消息
                                    try (PreparedStatement insertMessageStmt = conn.prepareStatement(
                                            "INSERT INTO system_messages (user_id, message_content, is_read, created_at) VALUES (?, ?, 0, NOW())")) {
                                        insertMessageStmt.setInt(1, userId);
                                        insertMessageStmt.setString(2, "您的候补订单 " + waitingId + " 已确认，请查看您的订单列表");
                                        insertMessageStmt.executeUpdate();
                                    }
                                }
                            });

                            System.out.println("候补订单已确认，用户已收到通知");
                            return true;
                        } catch (SQLException e) {
                            System.err.println("确认候补订单失败: " + e.getMessage());
                            return false;
                        }
                    }
                    return false;
                }, "SELECT wo.*, t.* " +
                        "FROM waiting_orders wo " +
                        "JOIN tickets t ON wo.ticket_id = t.ticket_id " +
                        "WHERE wo.waiting_id = ? AND wo.status = 'pending'", waitingId);

                if (!orderProcessed) {
                    System.out.println("处理候补订单失败，请检查订单ID是否正确或订单状态");
                }
            } else {
                System.out.println("已取消操作");
            }
        } catch (SQLException e) {
            System.err.println("确认候补订单失败: " + e.getMessage());
        }
    }


    // 管理员取消候补订单
    private static void cancelWaitingOrderByAdmin(String waitingId) {
        try {
            System.out.print("确认要取消该候补订单吗? (y/n): ");
            String confirm = scanner.nextLine();

            if ("y".equalsIgnoreCase(confirm)) {
                // 获取候补订单信息
                Boolean orderCancelled = ConcurrentDBUtil.executeQuery(rs -> {
                    if (rs.next()) {
                        int userId = rs.getInt("user_id");

                        // 开始事务处理
                        try {
                            ConcurrentDBUtil.executeInTransaction(conn -> {
                                // 更新候补订单状态为已取消
                                try (PreparedStatement updateWaitingStmt = conn.prepareStatement(
                                        "UPDATE waiting_orders SET status = 'cancelled' WHERE waiting_id = ?")) {
                                    updateWaitingStmt.setString(1, waitingId);
                                    updateWaitingStmt.executeUpdate();
                                }

                                // 添加系统消息
                                try (PreparedStatement insertMessageStmt = conn.prepareStatement(
                                        "INSERT INTO system_messages (user_id, message_content, is_read, created_at) VALUES (?, ?, 0, NOW())")) {
                                    insertMessageStmt.setInt(1, userId);
                                    insertMessageStmt.setString(2, "您的候补订单 " + waitingId + " 已被管理员取消");
                                    insertMessageStmt.executeUpdate();
                                }
                            });

                            System.out.println("候补订单已取消，用户已收到通知");
                            return true;
                        } catch (SQLException e) {
                            System.err.println("取消候补订单失败: " + e.getMessage());
                            return false;
                        }
                    }
                    return false;
                }, "SELECT wo.*, t.* " +
                        "FROM waiting_orders wo " +
                        "JOIN tickets t ON wo.ticket_id = t.ticket_id " +
                        "WHERE wo.waiting_id = ? AND wo.status = 'pending'", waitingId);

                if (!orderCancelled) {
                    System.out.println("取消候补订单失败，请检查订单ID是否正确或订单状态");
                }
            } else {
                System.out.println("已取消操作");
            }
        } catch (SQLException e) {
            System.err.println("取消候补订单失败: " + e.getMessage());
        }
    }



    // 取消候补订单
    private static boolean cancelWaitingOrder(String waitingId, int userId) {
        try {
            System.out.print("确认要取消该候补订单吗? (y/n): ");
            String confirm = scanner.nextLine();

            if ("y".equalsIgnoreCase(confirm)) {
                int result = ConcurrentDBUtil.executeUpdate(
                        "UPDATE waiting_orders SET status = 'cancelled' WHERE waiting_id = ? AND user_id = ?",
                        waitingId, userId);

                if (result > 0) {
                    System.out.println("候补订单已取消");
                    return true; // 返回true表示取消成功
                } else {
                    System.out.println("取消候补订单失败，请检查订单ID是否正确");
                    return false; // 返回false表示取消失败
                }
            } else {
                System.out.println("已保留候补订单");
                return false; // 返回false表示用户取消操作
            }
        } catch (SQLException e) {
            System.err.println("取消候补订单失败: " + e.getMessage());
            return false; // 返回false表示发生异常
        }
    }


    // 查看候补历史
    private static void viewWaitingHistory(int userId) {
        try {
            // 使用新的API，通过回调函数处理ResultSet
            Boolean hasOrders = ConcurrentDBUtil.executeQuery(rs -> {
                        System.out.println("\n===== 候补历史 =====");
                        boolean found = false;
                        while (rs.next()) {
                            found = true;
                            System.out.printf("[%s] %s → %s | %s | %s | %s | 状态: %s | 提交时间: %s\n",
                                    rs.getString("waiting_id"),
                                    rs.getString("departure"),
                                    rs.getString("destination"),
                                    rs.getString("time"),
                                    rs.getString("time_slot"),
                                    rs.getString("seat_class"),
                                    rs.getString("status"),
                                    rs.getTimestamp("created_at"));
                        }
                        return found;
                    }, "SELECT wo.*, t.* " +
                            "FROM waiting_orders wo " +
                            "JOIN tickets t ON wo.ticket_id = t.ticket_id " +
                            "WHERE wo.user_id = ? AND wo.status = 'cancelled' " +
                            "ORDER BY wo.created_at DESC",
                    userId);

            if (!hasOrders) {
                System.out.println("暂无候补历史");
            }

            System.out.print("\n按回车键返回...");
            scanner.nextLine();
        } catch (SQLException e) {
            System.err.println("查询候补历史失败: " + e.getMessage());
        }
    }


    // 查看用户订单
    private static void viewUserOrders(String token) {
        try {
            User user = UserSessionManager.getSession(token);
            if (user == null) {
                System.out.println("用户未登录或会话过期");
                return;
            }

            // 使用新的API，通过回调函数处理ResultSet
            Boolean hasOrders = ConcurrentDBUtil.executeQuery(rs -> {
                        System.out.println("\n===== 我的订单 =====");
                        boolean found = false;
                        while (rs.next()) {
                            found = true;
                            System.out.printf("[%s] %s → %s | %s | %s | ¥%.2f | 座位等级: %s | 预订时间: %s\n",
                                    rs.getString("ticket_id"),
                                    rs.getString("departure"),
                                    rs.getString("destination"),
                                    rs.getString("time"),
                                    rs.getString("time_slot"),
                                    rs.getDouble("price"),
                                    rs.getString("seat_class"),
                                    rs.getTimestamp("created_at"));
                        }
                        return found;
                    }, "SELECT t.*, ut.seat_class, ut.created_at " +
                            "FROM user_tickets ut " +
                            "JOIN tickets t ON ut.ticket_id = t.ticket_id " +
                            "WHERE ut.user_id = ? " +
                            "ORDER BY ut.created_at DESC",
                    user.getId());

            if (!hasOrders) {
                System.out.println("暂无订单");
            }
        } catch (SQLException e) {
            System.err.println("查询订单失败: " + e.getMessage());
        }
    }

    // 查看系统消息
    private static void viewSystemMessages(String token) {
        try {
            User user = UserSessionManager.getSession(token);
            if (user == null) {
                System.out.println("用户未登录或会话过期");
                return;
            }

            // 使用新的API，通过回调函数处理ResultSet
            Boolean hasMessages = ConcurrentDBUtil.executeQuery(rs -> {
                        System.out.println("\n===== 系统消息 =====");
                        boolean found = false;
                        while (rs.next()) {
                            found = true;
                            System.out.printf("[%s] %s\n",
                                    rs.getTimestamp("created_at"),
                                    rs.getString("message_content"));
                        }
                        return found;
                    }, "SELECT * FROM system_messages " +
                            "WHERE user_id = ? " +
                            "ORDER BY created_at DESC " +
                            "LIMIT 10",
                    user.getId());

            if (!hasMessages) {
                System.out.println("暂无系统消息");
                return;
            }

            // 标记消息为已读
            System.out.print("\n是否标记所有消息为已读? (y/n): ");
            String choice = scanner.nextLine();
            if ("y".equalsIgnoreCase(choice)) {
                ConcurrentDBUtil.executeUpdate(
                        "UPDATE system_messages SET is_read = 1 WHERE user_id = ? AND is_read = 0",
                        user.getId());
                System.out.println("所有消息已标记为已读");
            }
        } catch (SQLException e) {
            System.err.println("查询系统消息失败: " + e.getMessage());
        }
    }


    // 退票功能
    private static void refundTicket(String token) {
        try {
            User user = UserSessionManager.getSession(token);
            if (user == null) {
                System.out.println("用户未登录或会话过期");
                return;
            }

            // 显示用户订单
            Boolean hasOrders = ConcurrentDBUtil.executeQuery(rs -> {
                        System.out.println("\n===== 我的订单 =====");
                        boolean found = false;
                        while (rs.next()) {
                            found = true;
                            System.out.printf("%s → %s | %s | %s | %s | ¥%.2f | 座位等级: %s | 预订时间: %s\n",
                                    rs.getString("ticket_id"),
                                    rs.getString("departure"),
                                    rs.getString("destination"),
                                    rs.getString("time"),
                                    rs.getString("time_slot"),
                                    rs.getDouble("price"),
                                    rs.getString("seat_class"),
                                    rs.getTimestamp("created_at"));
                        }
                        return found;
                    }, "SELECT ut.user_id, t.*, ut.seat_class, ut.created_at " +
                            "FROM user_tickets ut " +
                            "JOIN tickets t ON ut.ticket_id = t.ticket_id " +
                            "WHERE ut.user_id = ? " +
                            "ORDER BY ut.created_at DESC",
                    user.getId());

            if (!hasOrders) {
                System.out.println("暂无订单");
                return;
            }

            System.out.print("\n请输入要退票的车票ID: ");
            String ticketId = scanner.nextLine();

            // 执行退票
            ConcurrentDBUtil.executeInTransaction(conn -> {
                // 获取订单信息
                try (PreparedStatement stmt = conn.prepareStatement(
                        "SELECT ut.*, t.ticket_id FROM user_tickets ut " +
                                "JOIN tickets t ON ut.ticket_id = t.ticket_id " +
                                "WHERE ut.ticket_id = ? AND ut.user_id = ?")) {
                    stmt.setString(1, ticketId);
                    stmt.setInt(2, user.getId());

                    try (ResultSet rs = stmt.executeQuery()) {
                        if (!rs.next()) {
                            System.out.println("无效的车票ID或您没有购买该车票");
                            return;
                        }

                        String seatClass = rs.getString("seat_class");

                        // 删除订单
                        try (PreparedStatement deleteStmt = conn.prepareStatement(
                                "DELETE FROM user_tickets WHERE ticket_id = ? AND user_id = ?")) {
                            deleteStmt.setString(1, ticketId);
                            deleteStmt.setInt(2, user.getId());
                            deleteStmt.executeUpdate();
                        }

                        // 恢复余票
                        try (PreparedStatement updateStmt = conn.prepareStatement(
                                "UPDATE tickets SET available_seats = available_seats + 1 " +
                                        "WHERE ticket_id = ? AND seat_class = ?")) {
                            updateStmt.setString(1, ticketId);
                            updateStmt.setString(2, seatClass);
                            updateStmt.executeUpdate();
                        }

                        System.out.println("退票成功！");
                    }
                }
            });
        } catch (SQLException e) {
            System.err.println("退票失败: " + e.getMessage());
        }
    }

}